﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.Common;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.Common;
using DHQGHN.MVC.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.PM0.Common.Helpers;
using DHQGHN.PM0.Controllers;
using DHQGHN.PM0.Models.Admin;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class MenuController : BaseController
    {
        MenuBO menuBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(MenuController));
        /// <summary>
        /// Action tra ve trang Quan ly chuc nang
        /// </summary>
        /// <param name="mModel">Menu Model</param>
        /// <param name="pageIndex">So thu tu trang danh sach</param>
        /// <param name="sort">Truong thong tin dung de sap xep</param>
        /// <param name="sortDir">Kieu sap xep</param>
        /// <param name="currentId">Khoa chinh ban ghi duoc yeu cau</param>
        /// <returns>Tra ve trang Quan ly chuc nang</returns>
        public ActionResult Index(MenuModel mModel = null, int pageIndex = 0, string sort = "MenuId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                SetActiveMenu("/Menu/Index");
                if (mModel == null) mModel = new MenuModel();
                IEnumerable<SelectListItem> lstTemp = CommonData.getListApp(Resources.Localization.AppText, Resources.Localization.AppTextValue);
                ViewBag.lstApp = lstTemp;
                IEnumerable<SelectListItem> lstTemp1 = CommonData.GetAllMenuByParentID(0, 0);
                ViewBag.lstParentMenu = lstTemp1;

                //mac dinh load form thi hien thi menu dang su dung
                mModel.IsActive = 1;
                //mModel.ParentMenuId = int.Parse(lstTemp1.Last().Value);
                mModel.ParentMenuId = -1;
                var model = search(mModel, pageIndex, currentId, false);

                //ViewBag.lstRol = getListRole();
                return View("~/Views/Menu/Menu.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Action tim kiem Chuc nang
        /// </summary>
        /// <param name="mModel">Menu Model</param>
        /// <param name="pageIndex">So thu tu trang danh sach</param>
        /// <param name="sort">Truong thong tin dung de sap xep</param>
        /// <param name="sortDir">Kieu sap xep</param>
        /// <param name="currentId">Khoa chinh ban ghi duoc yeu cau</param>
        /// <returns>Tra ve trang Quan ly chuc nang</returns>
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionSearch(MenuModel mModel = null, int pageIndex = 0, string sort = "MenuId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                if (mModel == null) mModel = new MenuModel();

                var model = search(mModel, pageIndex, currentId, false);
                return PartialView("~/Views/Menu/_MenuList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Action chuan bi du lieu Them moi/Cap nhat chuc nang
        /// </summary>
        /// <param name="menuId">Khoa ban ghi duoc cap nhat</param>
        /// <returns>Tra ve trang Them moi/Cap nhat</returns>
        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdateMenu(int? menuId)
        {
            try
            {
                MenuModel menu = null;
                RoleBO roleBO = new RoleBO();
                var lstType = roleBO.GetAll();

                if (menuId != null && menuId > 0)
                {
                    //Lay model de cap nhat
                    menuBO = new MenuBO();
                    menu = new MenuModel(menuBO.GetMenuById(menuId));
                    ViewBag.lstMenu = getListMenu(menu.AppId);
                    //GetMenuByParentID
                    ViewBag.lstMenu = CommonData.GetAllMenuByParentID(menu.AppId, 0);
                }
                if (menu == null)
                {
                    //Khoi tao model them moi
                    menu = new MenuModel()
                    {
                        MenuName = string.Empty,
                        MenuCode = string.Empty,
                        MenuDescription = string.Empty,
                        MenuUrl = string.Empty,
                        AppId = 0,
                        AppName = string.Empty,
                        ParentMenuId = 0,
                        ClassName = string.Empty,
                        IsActive = 1,
                        MenuOrder = 0
                    };
                    ViewBag.lstMenu = getListMenu(null);
                }
                ViewBag.lstApp = CommonData.getListApp(Resources.Localization.AppText, Resources.Localization.AppTextValue);

                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/Menu/_MenuModel.cshtml", menu);
                }

                return View(menu);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Action Them moi/Cap nhat chuc nang
        /// </summary>
        /// <param name="model">Chuc nang duoc Them moi/Cap nhat</param>
        /// <returns>Json the hien ket qua cap nhat</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult actionCreateOrUpdateMenu(MenuModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    menuBO = new MenuBO();
                    bool result = menuBO.createOrUpdateMenu(model.toDALModel());
                    if (result)
                    {
                        //Tra ve thong bao luu du lieu thanh cong
                        LogStream.Write<MenuModel>(GetCurrentUserName(),
                          CommonData.AppName,
                          GetFunction(),
                          Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateMenu", model);

                        return Json(JsonResponse.Json200(Resources.Localization.Confirm_Save_Success));
                    }
                    else
                    {
                        //Tra ve thong bao luu du lieu loi
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// <summary>
        /// Action xoa chuc nang
        /// </summary>
        /// <param name="ids">Danh sach ID ban ghi duoc xoa</param>
        /// <returns>Tra ve ket qua xoa du lieu</returns>
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(int[] ids)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    menuBO = new MenuBO();
                    bool result = menuBO.deleteMenu(ids);
                    if (result)
                    {
                        //Tra ve ket qua thanh cong
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(ids),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");
                        return Json(JsonResponse.Json200("Ngừng sử dụng thành công"));
                    }
                    else
                    {
                        //Tra ve ket qua loi
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// <summary>
        /// Kiem tra su ton tai cua chuc nang
        /// </summary>
        /// <param name="model">Model duoc kiem tra</param>
        /// <returns>True neu Chuc nang da ton tai; False neu Chuc nang khong ton tai</returns>
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult checkMenuExist(MenuModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    menuBO = new MenuBO();
                    bool result = menuBO.checkMenuExist(model.MenuId, model.MenuCode, model.MenuName, model.MenuUrl, model.AppId);
                    if (result)
                    {
                        //Tra ve true neu chuc nang da ton tai
                        return Json(JsonResponse.Json200(true));
                    }
                    else
                    {
                        //Tra ve false neu chuc nang chua ton tai
                        return Json(JsonResponse.Json200(false));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// <summary>
        /// Lay danh sach chuc nang thuoc mot Ung dung
        /// </summary>
        /// <param name="appId">Ma ung dung</param>
        /// <returns>Tra ve view chua danh sach menu</returns>
        public ActionResult reloadParentMenu(int appId)
        {
            try
            {
                MenuModel menu = null;
                if (menu == null)
                {
                    menu = new MenuModel()
                    {
                        MenuName = string.Empty,
                        MenuCode = string.Empty,
                        MenuDescription = string.Empty,
                        MenuUrl = string.Empty,
                        AppId = 0,
                        AppName = string.Empty,
                        ClassName = string.Empty,
                        ParentMenuId = 0,
                        IsActive = 1
                    };
                }

                //Lay danh sach menu
                ViewBag.lstMenu = getListMenu(appId);
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/Menu/_ParentMenuList.cshtml", menu);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// <summary>
        /// Action lay danh sach menu dang Json
        /// </summary>
        /// <param name="appId"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetListMenu(int appId)
        {
            try
            {
                var menus = getListMenu(appId);
                return Json(menus, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Tim kiem du lieu
        /// </summary>
        /// <param name="mModel">Menu model</param>
        /// <param name="pageIndex">So thu tu trang du lieu</param>
        /// <param name="currentId">Ma khoa ban ghi chuc nang</param>
        /// <returns>Page model</returns>
        private DataPage<MenuModel> search(MenuModel mModel, int pageIndex, int currentId, bool compareEqual)
        {
            try
            {
                menuBO = new MenuBO();
                //Lay danh sach chuc nang theo dieu kien tim kiem
                var DALModel = menuBO.GetDynamicListPaging(mModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var model = new DataPage<MenuModel>();
                var lstItem = DALModel.Data;
                //Chuyen kieu model
                foreach (DHQGHN.DAL.Models.Admin.MenuModel app in lstItem)
                {
                    model.Data.Add(new MenuModel(app));
                }

                MenuModel menuModel = null;
                if (currentId >= 0 && model.Data.Count > 0)
                {
                    //Lay model trong truong hop cung cap ma khoa ban ghi chuc nang can lay
                    menuModel = model.Data.Find(user => user.AppId == currentId);
                    model.CustomData = menuModel;
                }
                else
                {
                    model.CustomData = mModel;
                }
                if (model.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "Menu",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "menu-list",

                    };
                    pagNative.TotalRows = model.Data[0].RecordCount;
                    pagNative.CurrentRow = model.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return model;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public JsonResult GetMenuByParentID(string strAppID)
        {
            try
            {
                int intAppID = 0;
                if (string.IsNullOrEmpty(strAppID))
                {
                    intAppID = 0;
                }
                else { 
                    intAppID = int.Parse(strAppID);
                }
                IEnumerable<SelectListItem> lstTemp1 = CommonData.GetAllMenuByParentID(intAppID, 0);

                return Json(lstTemp1, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                //logger.Error(ex.ToString());
                throw;
                //return null;
            }

        }

        private IEnumerable<SelectListItem> getListMenu(int? appId)
        {
            try
            {
                MenuBO menuBO = new MenuBO();

                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = "0",
                    Text = "Chọn chức năng cha"
                });
                if (appId != null && appId > 0)
                {
                    var lstMenu = menuBO.GetAllMenuByAppId(appId.Value);
                    foreach (var menu in lstMenu)
                    {
                        lstItems.Add(new SelectListItem
                        {
                            Value = menu.MenuId.ToString(),
                            Text = menu.MenuName
                        });
                    }
                }
                return new SelectList(lstItems, "Value", "Text");
            }
            catch
            {
                throw;
            }
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult ActionActive(string id)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    menuBO = new MenuBO();
                    bool result = menuBO.activeMenu(id);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(new string[] { id }),
                            Resources.Localization.ActionActiveCaption + " - ActionActive");

                        return Json(JsonResponse.Json200("Khôi phục thành công"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public JsonResult CheckExistName(string MenuName, int? MenuId, int AppId)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(MenuName))
                {
                    MenuModel _menumodel = new MenuModel()
                    {
                        MenuName = MenuName.Trim(),
                        AppId = AppId,
                        IsActive = 2
                    };
                    var model = search(_menumodel, 0, -1, true);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (MenuModel menu in lstItem)
                        {
                            if (MenuId != null && MenuId > 0)
                            {
                                if (menu.MenuId != MenuId)
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public JsonResult CheckExistCode(string MenuCode, int? MenuId, int AppId)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(MenuCode))
                {
                    MenuModel _menumodel = new MenuModel()
                    {
                        MenuCode = MenuCode,
                        AppId = AppId,
                        IsActive = 2
                    };
                    var model = search(_menumodel, 0, -1, true);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (MenuModel menu in lstItem)
                        {
                            if (MenuId != null && MenuId > 0)
                            {
                                if (menu.MenuId != MenuId)
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public JsonResult CheckExistMenuUrl(string MenuUrl, int? MenuId, int AppId, int ParentMenuId)
        {
            try
            {
                if (MenuUrl == "#" && ParentMenuId == 0)
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
                var isExist = false;
                if (!string.IsNullOrEmpty(MenuUrl))
                {
                    MenuModel _menumodel = new MenuModel()
                    {
                        MenuUrl = MenuUrl,
                        AppId = AppId,
                        IsActive = 2
                    };
                    var model = search(_menumodel, 0, -1, true);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (MenuModel menu in lstItem)
                        {
                            if (MenuId != null && MenuId > 0)
                            {
                                if (menu.MenuId != MenuId)
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private string GetFunction()
        {
            return "Quản trị chức năng - MenuController";
        }
    }
}